<?php

namespace Common\Model;

use Common\Lib\Upload\ImgManager;
use Think\Model;

class CategoryModel extends Model
{
    protected $_validate = array(
        array('c_title', 'require', '名称必须填写！', 1),
    );

    protected $_auto = array(//array('addtime','time',1,'function'),
    );

    public function get_list($map = array(), $sort = '', $fields = '')
    {
        $items = $this->field($fields)->where($map)->order($sort)->select();
        if (!empty($items)) {
            $items = array_map(array($this, 'fill'), $items);
        }
        return $items;
    }

    public function fill($item)
    {
        if ($item['c_pid'] > 0) {
            $item['qurl'] = RU('question/lists', array('cat' => $item['c_pid'], 'cat1' => $item['c_id']));
            $item['aurl'] = RU('article/lists', array('cat' => $item['c_pid'], 'cat1' => $item['c_id']));
            $item['burl'] = RU('bbs/lists', array('cat' => $item['c_pid'], 'cat1' => $item['c_id']));
        } else {
            $item['qurl'] = RU('question/lists', array('cat' => $item['c_id']));
            $item['aurl'] = RU('article/lists', array('cat' => $item['c_id']));
            $item['burl'] = RU('bbs/lists', array('cat' => $item['c_id']));
        }
        $item['c_pic'] = D('Category')->get_img_src($item['c_pic']);

        return $item;
    }

    /**
     * 生成分类的图标src
     * @param string $c_pic
     * @return string
     */
    public function get_img_src($c_pic)
    {
        $c_pic = $c_pic ?: 'null.png';
        if (is_numeric($c_pic)) {
            $src = ImgManager::make($c_pic)->url();
        } else {
            $src = __ROOT__ . '/' . C('YTATA_IMG_CATEGORY_DIR') . $c_pic;
        }
        return $src;
    }

        /**
         * 获取分类层级
         * @param string $type 分类类型 '1'-问题 '2'-文章 ···
         * @return string 返回分类层级 ’0‘-分类不存在 '1'-单层 ’2‘-双层
         */
        public function get_cat_level($type = '1')
        {
            $map['c_type'] = intval($type);
            $map['c_pid'] = 0;
            $list = M("Category")->where($map)->select();
            if (empty($list)) {
                return '0';
            }
            foreach ($list as $val) {
                $cmap['c_pid'] = intval($val['c_id']);
                $info = M("Category")->where($cmap)->select();
                if (!empty($info)) {
                    return '2';
                }
            }
            return '1';
        }
}